import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.header import Header
from email.encoders import encode_base64
import pub_readconf
import pub_config


class SendMail():
    def __init__(self, msgdata, filepath, filename):
        """
        这是一个发送邮件的类，需要2个参数
        :param msgdata: 邮件正文
        :param filepath: 附件路径
        """
        rc = pub_readconf.ReadConf(os.path.join(pub_config.ROOT_PATH, "conf/default.yml"))
        rc_data = rc.read_yaml()
        self.mail_host = rc_data['mail_host']
        self.mail_port = rc_data['mail_port']
        self.mail_sender = rc_data['mail_sender']
        self.mail_pwd = rc_data['mail_pwd']
        self.mail_receiver = rc_data['mail_receiver']
        self.msgdata = msgdata
        self.filepath = filepath
        self.filename = filename
        # 创建SMTP对象
        svc = smtplib.SMTP()
        # 连接邮箱服务器
        svc.connect(self.mail_host, self.mail_port)
        # 登录邮箱
        # svc.starttls()  # 启动TLS加密传输
        svc.login(self.mail_sender, self.mail_pwd)
        self.svc = svc

    def send_email(self):
        # 创建一个MIMEMultipart对象，用于构建邮件内容
        message = MIMEMultipart()
        message['From'] = Header("摇光机器人", 'utf-8')  # 发件人邮箱地址
        message['To'] = Header("靓仔", 'utf-8')  # 收件人邮箱地址
        subject = '【摇光】巡检报告'
        message['Subject'] = Header(subject, 'utf-8')

        # 邮件正文内容
        mail_content = self.msgdata

        # message.attach(MIMEBase('text', 'plain', 'utf-8'))
        message.attach(MIMEText(mail_content, 'plain', 'utf-8'))

        # 读取文件并添加为附件
        with open(self.filepath, 'rb') as file:
            attachment = MIMEBase('application', 'octet-stream')
            attachment.set_payload(file.read())
            encode_base64(attachment)
            attachment.add_header('Content-Disposition', 'attachment', filename=self.filename)
            message.attach(attachment)
        # 发送邮件
        try:
            self.svc.sendmail(self.mail_sender, self.mail_receiver, message.as_string())
            print("[INFO] 邮件发送成功")
        except smtplib.SMTPException as e:
            print("[ERROR] 邮件发送失败", e)
        finally:
            self.svc.quit()
            self.svc.close()
